package com.nd.rj.common.login.task;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import com.common.android.utils.task.progressTask.ProgressTask;
import com.nd.rj.common.ILogin99Listener;
import com.nd.rj.common.R;
import com.nd.rj.common.login.LoginPro;
import com.nd.rj.common.login.NdLogin99Assistant;
import com.nd.rj.common.login.DataDef.NdLoginConst;
import com.product.android.business.bean.UserInfo;

/**
 * 短信登录线程
 * 
 * <br>
 * Created 2014-9-4 下午3:29:37
 * 
 * @version V1.6
 * @author linsj
 * 
 * @see
 * 
 *      Copyright(c) 2009-2014, TQ Digital Entertainment, All Rights Reserved
 * 
 */
public class LoginNormalLoginTask extends ProgressTask {
    /** 等待对话框 */
    private Dialog mWaitDlg;

    /** 用户是否点击取消 */
    private boolean mbCanceled = false;

    /** 安全中心登录助手类 */
    private NdLogin99Assistant mLogin91Assistant;

    /** 登录回调监听 */
    private ILogin99Listener mLogin99Listener;

    /** 图形验证码 */
    private String mstrImgCheckCode;

    /** 每秒的毫秒数 */
    private final int MILLI_SECOND_PER_SECOND = 1000;

    /** 用户信息，登录成功后返回该值 */
    private UserInfo mUserInfo;

    /** 登录类型 */
    private int miLoginType = NdLoginConst.LOGIN_TYPE_UAP;
    
    /** 是否先用ticket登录 */
    private boolean mbIsTicketFirst = false;
    
    /**
     * 获得等待框
     * 
     * <br>Created 2014-10-30 下午1:51:53
     * @author       linsj
     */
    private void getDialogIteration(){
        if(null != mWaitDlg){
            progressDialogIteration = new IProgressDialogIteration() {
                @Override
                public void onShow() {
                    mWaitDlg.setCanceledOnTouchOutside(false);
                    mWaitDlg.setOnKeyListener(new OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                            // 屏蔽Search键(因为按搜索按键会被关闭)
                            switch (event.getKeyCode()) {
                            case KeyEvent.KEYCODE_SEARCH:
                                return true;
                            case KeyEvent.KEYCODE_BACK:
                                mbCanceled = true;
                                mWaitDlg.dismiss();
                                return true;
                            default:
                                return false;
                            }
                        }
                    });

                    mWaitDlg.show();
                }

                @Override
                public void onDismiss() {
                    mWaitDlg.dismiss();
                }
            };
        }
    }

    /**
     * 构造方法 Creates a new instance of LoginMsgLoginTask. <br>
     * Created 2014-9-5 下午4:03:08
     * 
     * @param context
     *            上下文
     * @param loginAssistant
     *            登录助手
     * @param login99Listener
     *            登录监听
     * @param userInfo
     *            用户信息
     * @param strImgCheckCode
     *            图形验证码
     * @param bIsTicketFirst
     *            是否优先票据登录
     * @param waitDlg
     *            等待对话框
     */
    public LoginNormalLoginTask(Context context, NdLogin99Assistant loginAssistant,
            ILogin99Listener login99Listener, UserInfo userInfo,
            String strImgCheckCode, boolean bIsTicketFirst, Dialog waitDlg) {
        super(context, R.string.nd_login_logining);
        mLogin91Assistant = loginAssistant;
        mLogin99Listener = login99Listener;
        mUserInfo = userInfo;
        mstrImgCheckCode = strImgCheckCode;
        mbIsTicketFirst = bIsTicketFirst;
        mWaitDlg = waitDlg;
        
        getDialogIteration();
    }

    @Override
    protected void doSuccess() {
        if (mbCanceled) {
            return;
        }

        // 结束后回调
        if (mLogin99Listener != null) {
            mLogin99Listener.onLoginSuccess(mUserInfo);
        }
    }

    @Override
    protected void onCancelled() {
        mbCanceled = true;
        super.onCancelled();
    }

    @Override
    protected Integer doInBackground(Void... params) {
        mbCanceled = false;
        int code = 0;
        while (true) {
            if (mbIsTicketFirst) {
                // 优先使用票据登录
                code = LoginPro.getInstance(mContext).userLoginByTicket(miLoginType, mUserInfo, null,
                        mErrorMsg);
                if (code == 0 || mLogin91Assistant.isInitializing()) {
                    // 登录成功或者（未初始化完成只是使用票据登录），直接结束
                    break;
                }
            }

            if (mbCanceled) {
                break;
            }

            // 认证失败或者票据过期或者票据不存在,使用正常登录流程
            boolean isWaiting = mLogin91Assistant.isInitializing();
            while (mLogin91Assistant.isInitializing()) {
                // 等待初始化完成
                try {
                    isWaiting = true;
                    Thread.sleep(MILLI_SECOND_PER_SECOND);
                    Log.d("debug", "mLogin91Assistant.isInitializing");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (isWaiting) {
                if (!mLogin91Assistant.isInitSuccessful()) {
                    // 刚刚初始化完成且初始化失败
                    return mLogin91Assistant.getErrorCode();
                }
            }
            if (!mLogin91Assistant.isInitSuccessful()) {
                // 初始化异常，重新从初始化开始或者用户切换登录
                code = doFromInit();
                break;
            }

            if (mbCanceled) {
                break;
            }

            // 上一次初始化正常
            code = doFromLogin();

            if (mbCanceled) {
                break;
            }

            // 在登录的时候，有可能用户修改了时间导致时间戳不正确
            if (mLogin91Assistant.isNeedInit()) {
                Log.d("debug", "login code=" + code);
                // 返回包类型异常、会话超时、时间戳异常，全部重新初始化
                code = doFromInit();
                break;
            }
            break;
        }
        if (code == 0) {
            if (mLogin99Listener != null) {
                return mLogin99Listener.onLoginProccessing(mUserInfo);
            }
        }
        return code;
    }

    @Override
    protected void doFail(int result) {
        if (mbCanceled) {
            return;
        }

        String strErrMsg = "";
        if (null == mLogin91Assistant || null == mLogin99Listener) {
            strErrMsg = mContext.getResources().getString(R.string.login_unknow_error);
        } else {
            strErrMsg = mLogin91Assistant.getErrmsg();
            if (TextUtils.isEmpty(strErrMsg)) {
                try {
                    strErrMsg = mContext.getResources().getString(result);
                } catch (Exception e) {
                    strErrMsg = mContext.getResources().getString(R.string.login_unknow_error);
                }
            }
        }
        
        if (mLogin99Listener != null) {
            mLogin99Listener.onLoginFail(result, strErrMsg);
        }
    }

    private int doFromInit() {
        int code = mLogin91Assistant.doInit();
        if (code != 0) {
            return code;
        }
        code = doFromLogin();
        return code;
    }

    private int doFromLogin() {
        int code = mLogin91Assistant.doLogin(mUserInfo.getUserName(), mUserInfo.getUserPassMixedMd5(),
                mstrImgCheckCode);
        if (code == 0) {
            // 登录成功
            String cookie = mLogin91Assistant.getCookie();
            if (TextUtils.isEmpty(cookie)) {
                // cookie异常
                code = R.string.nd_login_cookie_400;
            } else {
                if (mbCanceled) {
                    return code;
                }
                StringBuilder receive = new StringBuilder();
                code = LoginPro.getInstance(mContext).userLoginByCookie(miLoginType, cookie,
                        mUserInfo, null, receive);
            }
        }
        return code;
    }
}
